<?php

use C\L\Task;
use C\M\Job;

class JobTask extends Task
{
    public function runAction()
    {
        $jobs = $this->getJobs();
        foreach ($jobs as $job) {
            try {
                $payload = json_decode($job->payload, true);
                switch ($job->event) {
                    case 'buy_slave_goods':
                        $this->buySlaveGoods($payload);
                        break;
                    default:
                        break;
                }
                $this->markAsCompleted($job);
            } catch (\Exception $error) {
                $this->markAsFailed($job);
            }
        }
    }

    private function getJobs()
    {
        $conditions = 'state = :state: AND scheduled_at <= :scheduled_at:';
        $bind = [
            'state'        => 'checkout',
            'scheduled_at' => Date('Y-m-d H:i:s'),
        ];
        $limit = [50, 0];

        return Job::find(compact('conditions', 'bind', 'limit'));
    }

    private function markAsCompleted($job)
    {
        $job->state = 'completed';
        $job->completed_at = date('Y-m-d H:i:s');

        return $job->save();
    }

    private function markAsFailed($job)
    {
        $job->state = 'failed';
        $job->failed_at = date('Y-m-d H:i:s');

        return $job->save();
    }

    private function buySlaveGoods($payload)
    {
        $userId        = $payload['user_id'];
        $slaveGoodsId  = $payload['slave_goods_id'];
        $masterOrderId = $payload['master_order_id'];
      
        $result = $this->s_group_buying_order->confirm($userId, $slaveGoodsId, 1, null, $masterOrderId);
        if (!$result) {
            throw new \Exception('购买复购商品失败');
        }

        return true;
    }
}
